import React, { Component, useState, useEffect } from "react";
import { Table, Input, InputNumber, Popconfirm, Form, message, Button, Select, Space, ConfigProvider } from 'antd';
import { Axios } from 'toolkit';
import zhCN from 'antd/es/locale/zh_CN';  // 引入中文包
import { PlusCircleTwoTone, SearchOutlined } from '@ant-design/icons';
import Item from 'antd/lib/list/Item';
import globalStoreData from '@/store';

const { Option } = Select;

interface Item {
  id: string;
  code: string;
  name: string;
  password: string;
  organizationId: string;
  userType: string;
  status: string;
  createTime: string;
  updateTime: string;
  operation: string;
}

interface Result {
  message: string,
  succeed: boolean,
  data: Page
}

interface Page {
  "toatlePage": number,
  "toatleCount": number,
  "pageSize": number,
  "values": Item[]
}
interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: 'number' | 'text';
  record: Item;
  index: number;
  children: React.ReactNode;
}


const EditableCell: React.FC<EditableCellProps> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  let data = JSON.parse(globalStoreData.getStore('SysEnumList'));
  let organizationId:any = [];
  let status:any = [];
  data.forEach((item:any) => {
    if(item.title === 'organization') {
      organizationId.push(item);
    }
    if(item.title === 'Status') {
      status.push(item);
    }
  })
  console.log(organizationId)
  const _getInputNode = (inputType: string) => {
    if (inputType === 'number') {
      return <InputNumber />;
    }
    if (inputType === 'organizationId') {
      return (<Select
        placeholder="请选择"
        optionFilterProp="children"
        onChange={() => { }}
        onFocus={() => { }}
        onBlur={() => { }}
        options={
          organizationId.map(item => {
            return {
              label: item.name,
              value: item.code
            }  
          })
        }
      
      >
        {/* {organizationId.map( value => (
          <Option  value={value.code}> {value.name} </Option>
        ))} */}
      </Select>);
    }
 
    if (inputType === 'status') {
      return (<Select
        // style={{ width: 200 }}
        placeholder="请选择"
        optionFilterProp="children"
        onChange={() => { }}
        onFocus={() => { }}
        onBlur={() => { }}
        options={
          status.map(item => {
            return {
              label: item.name,
              value: item.code
            }
          })
        }
      >
        {/* {
          status.map( value => (
            <Option key={value.code} value={value.code}> {value.name} </Option>
          ))
        } */}
      </Select>);
    }
    return <Input />;
  }
  // console.log(inputType,)
  const inputNode = _getInputNode(inputType);
  
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `请输入${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
          children
        )}
    </td>
  );
};

const OrganizationPage = () => {
  const searchRef = React.useRef<any>();
  const organizationIdRef = React.useRef<any>();
  const statusRef = React.useRef<any>();
  const [form] = Form.useForm();
  const [data, setData] = useState<Item[]>();
  const [page, setPage] = useState<number>(0);
  const [total, setTotal] = useState<number>(0);
  const [editingKey, setEditingKey] = useState('');
  
  const [organizationId, setOrganizationId] = useState('') // 搜索区划
  const [status, setStatus] = useState('') // 搜索状态
  const [searchValue, setSearchValue] = useState(); // 搜索框
  const pageSize: number = 5;
  let droplist = JSON.parse(globalStoreData.getStore('SysEnumList'));
  let sysorganizationId:any = [];
  let sysstatus:any = [];

  // 枚举下拉框
  droplist.forEach((item:any) => {
    if(item.title === 'organization') {
      sysorganizationId.push(item);
    }
    if(item.title === 'Status') {
      sysstatus.push(item);
    }
  })
  console.log(sysorganizationId)
  console.log(sysstatus)
  let sysdistrictOptions:any = sysorganizationId.map(item => {
    return {
      label: item.name,
      value: item.code
    }
  })
  let sysstatusOptions:any = sysstatus.map(item => {
      return {
        label: item.name,
        value: item.code
      }
    })
  

  const isEditing = (record: Item) => record.id === editingKey; 

  const edit = (record: Item) => {
    form.setFieldsValue({ ...record });
    setEditingKey(record.id);
  };

  const cancel =() => {
    setEditingKey('');
    if (editingKey === 'add') {
      let newData: any = [...data];
      newData.splice(0, 1);
      setData(newData)
    }
  }

  useEffect(() => {
    query();

    return () => { }
  }, [page])


  const query = () => {
    Axios.post('/userList', {
      limit: pageSize,
      pageNum: page
    },
    {headers: {
      'DISTRICT_CODE': 1111
    }}
    ).then(res => {
      let reslut: Result = res.data;
      if (!reslut.succeed) {
        message.error(reslut.message);
        return;
      }
      let resultData = reslut.data.values.map((item: Item, index: number) => {
        return {
          ...item, index: index + 1
        }
      })
      setData(resultData);
      setTotal(reslut.data.toatleCount);
      // console.log(page)

    }).catch(error => {
      console.error(error);
      message.error(error.message);
    })
  }

  // 点击 新增 出现输入框
  const openAdd = async (): Promise<void> => {
    try {
      if (editingKey !== '') {
        message.error('请先保存');
        return;
      }
      const row: any = {
        id: 'add', // 这里也是 add
        code: '',
        name: '',
        password: '',
        organizationId: '',
        userType: 0,
        status: 0,
        createTime: '',
        updateTime: '',
        operation: '',
      };
      const newData = [...data];
      newData.unshift(row)
      setData(newData);
      setEditingKey('add');

    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  // 编辑 和 新增
  const save = async (id: string) => {
    // 监听 数据 变化字段
    const row = (await form.validateFields()) as Item;
    // 拷贝 原始数据 复杂的 数据 可用 loadsh
    const newData = [...data];
    // 获取 新增 或编辑数据在原始数据中 下标
    const index = newData.findIndex(item => id === item.id);
    // 构建后端需要的 参数对象
    let params: any = {
      ...newData[index],
      ...row
    }
    // 判断是不是新增  
    if (id !== 'add') {
      // id不为add就是编辑
      Axios.post('/updateManageUser', params).then((res: any) => {
        if (res.data.succeed) {
          message.success('编辑成功');
          newData.splice(index, 1, params);
          setData(newData);
          setEditingKey('');
        } else {
          message.error(res.data.message)
        }
      }).catch((error) => {

      })
    } else {
      delete params.id;
      Axios.post('/addManageUser', params).then((res: any) => {
        if (res.data.succeed) {
          message.success('新增成功');
          newData.splice(index, 1, params);
          setData(newData);
          setEditingKey('');
          query();
        } else {
          message.error(res.data.message)
        }
      }).catch((error) => {

      })
    }
  };

  const del = async (id: string) => {
    try {
      const res = await Axios.post('/removeManageUser', { "id": id })
      let result = res.data

      if (result.succeed == true) {
        const newData = [...data];
        const index = newData.findIndex((item) => id === item.id);
        newData.splice(index, 1);
        query();
        setData(newData);
        setEditingKey('');
      } else {

        message.error(result.message);
      }
    } catch (error) {
      console.error(error);
    }

  };

  const columns = [
    {title: '行号', dataIndex: 'index', width: '5%', },
    {title: '用户编码', dataIndex: 'code', width: '10%', editable: true },
    {title: '用户名称', dataIndex: 'name', width: '10%', editable: true },
    {title: '所属机构', dataIndex: 'organizationId', width: '10%', editable: true },
    {title: '状态', dataIndex: 'status', width: '7%', editable: true,
      render: (v: number, record: status) =>
        v === 1 ? (
          <span >启用</span>
        ) : (
          <span >禁用</span>
        ),
    },
    { title: '创建时间', dataIndex: 'createTime', width: '15%', },
    { title: '更新时间', dataIndex: 'updateTime', width: '15%', },
    {
      title: '操作', dataIndex: 'operation', width: '8%',
      // 点击新增 editable  为true
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a href="javascript:;" onClick={() => save(record.id)} style={{ marginRight: 8 }}>
              保存
            </a>
            <a onClick={cancel}>取消</a>
          </span>
        ) : (
            <Space>
              <a disabled={editingKey !== ''} onClick={() => edit(record)}>
                编辑
              </a>
              <Popconfirm title="确认删除吗？" onConfirm={() => del(record.id)} okText="确定" cancelText="取消">
                <a>删除</a>
              </Popconfirm>
              <a href="">
                重置密码
              </a>

            </Space>
          );
      },
    },
  ];

const _getInputType = React.useCallback((dataIndex:string) =>{
  if(dataIndex === 'agdistrictIde') {
    return 'number';
  }
  if(dataIndex === 'organizationId') {
    return 'organizationId';
  }
  if(dataIndex === 'status') {
    return 'status';
  }
  return 'text';
},[])

  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        // 在这控制
        inputType: _getInputType(col.dataIndex),
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <ConfigProvider locale={zhCN}>
      <div>
        <Space className="div-search" style={{ margin: '20px 0' }}>
          <Input
            style={{ width: '200px' }}
            placeholder="请输入用户编码或用户名称"
            value={searchValue}
          ref={searchRef}
          onChange={(e) => {
            setSearchValue(e.currentTarget.value)
          }}
          />

          所划机构：
          <Select options={sysdistrictOptions} defaultValue="" style={{ width: '200px' }}
            ref={organizationIdRef}
            value={organizationId}
            onChange={(value) => {
              setOrganizationId(value)
            }}
          >
          </Select>
          状态：
          <Select options={sysstatusOptions} defaultValue="" style={{ width: '200px' }}
            ref={statusRef}
            value={status}
            onChange={(value) => {
              setStatus(value)
            }}
          >
           
          </Select>
          <Button type="primary" icon={<SearchOutlined />} onClick={() => {
          
          setSearchValue(searchRef.current.state.value)
          setOrganizationId(organizationIdRef.current.props.value)
          setStatus(statusRef.current.props.value)
          
          }}>
            搜索
          </Button>
        </Space >
        <div className="div-add">
          <Button type="primary" onClick={() => openAdd()} icon={<PlusCircleTwoTone />} style={{ marginBottom: '10px' }}>
            新建
          </Button>
          
        </div>
        <Form form={form} component={false}>
          <Table rowKey={(recode) => recode.id}
            style={{
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              cursor: 'pointer'
            }}
            size="middle"
            components={{
              body: {
                cell: EditableCell,
              },
            }}
            dataSource={data}
            columns={mergedColumns}
            rowClassName="editable-row"
            pagination={{
              showTotal: function showTotal(total) {
                return `总共 ${total} 条`;
              },
              pageSize: pageSize,
              onChange: (page, pageSize) => {

                console.log(page);
                setPage(page - 1);
              },
              showQuickJumper:true,
              total: total
              // pageSize: data.pageSize,
              // total: data.toatleCount

            }}
          />
        </Form>
      </div>
    </ConfigProvider>
  );
};


export default OrganizationPage;